// pages/epidemicsee/epidemicSee.js
const app = getApp();
// var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
// var WxParse = require('../../wxParse/wxParse.js');
// var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    textarea:[{
      id:"",
      deptAddress:'',
      latitude: "",
      longitude: "",
    }],
    setId:'',
    workStatus:false,
    delDetail:[],
    id:"",
    detail:"",
    time:"",
    orgName:"",
    workFirstStart: "00:00",
    workFirstEnd:"23:59",
    workSecondStart: "",
    workSecondEnd:"",
    homeFirstStart: "00:00",
    homeFirstEnd:"23:59",
    homeSecondStart:"",
    homeSecondEnd:"",
    lock:false,
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  //增加联系人
  addGroup() {
    if (this.data.textarea.length < 10) {
      this.data.textarea.push({
        id: "",
        deptAddress: '',
        latitude: "",
        longitude: "",
      })
    }
    this.setData({
      textarea: this.data.textarea
    })
  },
  //移除联系人
  removeGroup(e) {
    var id = e.currentTarget.dataset.id;
    this.removeArray(this.data.textarea, e.currentTarget.dataset.add);
    if(id){
      this.data.delDetail.push(id);
      this.toggle("delDetail", this.data.delDetail)
    }
  },
  //移除数组
  removeArray(_arr, _obj) {
    var length = _arr.length;
    for (var i = 0; i < length; i++) {
      if (_arr[i].deptAddress == _obj) {
        if (i == 0) {
          _arr.shift(); //删除并返回数组的第一个元素
          return this.setData({
            textarea: _arr
          });
        }
        else if (i == length - 1) {
          _arr.pop();  //删除并返回数组的最后一个元素
          return this.setData({
            textarea: _arr
          });
        }
        else {
          _arr.splice(i, 1); //删除下标为i的元素
          return this.setData({
            textarea: _arr
          });
        }
      }
    }
  },
  changeSwitch(e) {
    var key = e.currentTarget.dataset.key;
    this.toggle(key, e.detail.value * 1);
  },
  bindDateChange: function (e) {
    var key = e.currentTarget.dataset.key;
    var date = e.detail.value;
    var a = date.split(":");
    var time = new Date().setHours(a[0], a[1]) + 1 * 60 * 1000;
    var next = new Date(time).format("hh:mm");
    this.toggle(key, date);
    if (e.currentTarget.dataset.end){
      var end = e.currentTarget.dataset.end;
      this.toggle(end, next);
    }
  },
  //获取授权
  judgeAuthorization(e) {
    console.log("打开地图")
    var index = e.currentTarget.dataset.index;
    var that = this;
    wx.getSetting({
      success(res) {
        //首次调起授权
        if (res.authSetting['scope.userLocation']) {
          wx.showToast({
            title: '',
            icon: 'loading'
          });
          that.openMap(index)
        } else {
          //手动授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.showToast({
                title: '',
                icon: 'loading'
              });
              that.openMap(index)
            },
            fail() {
              wx.showModal({
                title: '提示',
                content: '检测到您未授权一起来往获取您的位置信息，是否前往设置？',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      complete(res) {
                        if (res.authSetting['scope.userLocation']) {
                          that.openMap(index);
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        }
      },
    })
  },
  //调起地图组件
  openMap(index) {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        wx.hideToast();
        var latitude = res.latitude
        var longitude = res.longitude
        wx.chooseLocation({
          latitude: latitude,
          longitude: longitude,
          scale: 14,
          success: function (res) {
            console.log(res)
            //获取地址信息
            var deptAddress = 'textarea[' + index + '].deptAddress';
            var latitude = 'textarea[' + index + '].latitude'; 
            var longitude = 'textarea[' + index + '].longitude'; 
            that.setData({
              [deptAddress]: res.name,
              [latitude]: res.latitude,
              [longitude]: res.longitude,
            })
          },
        })
      },
      fail: function (res) {
        wx.hideToast();
        wx.showModal({
          title: '',
          content: '无法获取你的位置信息。请到手机系统的[设置]->[隐私]->[定位服务]中打开定位服务，并允许微信使用定位服务。',
          showCancel: false,
          confirmText: '确定',
          success: function (res) {
          }
        })
      }
    })
  },
  detail: function () {
    var that = this;
    app.req({
      url: "orgmini/epidemic/epidemicRelation",
      data: {
        relationId: that.data.id,
        type: 1,
      },
      success: function (res) {
        if (200 == res.code) {
          that.toggle("orgName", res.data.relationName);
          that.toggle("orgUrl", res.data.relationUrl);
        }
      }
    });
  },
  timeDeal(time1,time2){
    console.log(time1, time2)
    var a = time1.split(":");
    var b = time2.split(":");
    return new Date().setHours(a[0], a[1]) > new Date().setHours(b[0], b[1])
  },
  // 提交数据
  submit(){
    if (this.data.lock){
      return
    }
    var that = this;
    var title = "";
    for (var i in this.data.textarea){
      if (!this.data.textarea[i].deptAddress){
        title = `请管理员设置公司办公地址${ parseInt(i) + 1 }`;
        wx.showToast({
          title: title,
          icon:"none",
          duration:3000
        })
        return
      }
    }
    if (!this.data.workFirstStart){
      title = "请设置工作打卡时间第一次打卡开始时间"
    } else if (!this.data.workFirstEnd){
      title = "请设置工作打卡时间第一次打卡结束时间"
    } else if (this.timeDeal(this.data.workFirstStart, this.data.workFirstEnd)) {
      title = "工作打卡时间第一次打卡结束时间要大于其开始时间"
    }else if (this.data.workStatus == 1 && !this.data.workSecondStart) {
      title = "请设置工作打卡时间第二次打卡开始时间"
    } else if (this.data.workStatus == 1 && this.timeDeal(this.data.workFirstEnd, this.data.workSecondStart)) {
      title = "时间设置存在重叠，请调整后再试"
    }else if (this.data.workStatus == 1 && !this.data.workSecondEnd) {
      title = "请设置工作打卡时间第二次打卡结束时间"
    } else if (this.data.workStatus == 1 && this.timeDeal(this.data.workSecondStart, this.data.workSecondEnd)) {
      title = "工作打卡时间第二次打卡结束时间要大于其开始时间"
    } else if (!this.data.homeFirstStart) {
      title = "请设置居家打卡时间第一次打卡开始时间"
    } else if (!this.data.homeFirstEnd) {
      title = "请设置居家打卡时间第一次打卡结束时间"
    } else if (this.timeDeal(this.data.homeFirstStart, this.data.homeFirstEnd)) {
      title = "居家打卡时间第一次打卡结束时间要大于其开始时间"
    } else if (this.data.homeStatus == 1 && !this.data.homeSecondStart) {
      title = "请设置居家打卡时间第二次打卡开始时间"
    } else if (this.data.homeStatus == 1 && this.timeDeal(this.data.homeFirstEnd, this.data.homeSecondStart)) {
      title = "时间设置存在重叠，请调整后再试"
    } else if (this.data.homeStatus == 1 && !this.data.homeSecondEnd) {
      title = "请设置居家打卡时间第二次打卡结束时间"
    } else if (this.data.homeStatus == 1 && this.timeDeal(this.data.homeSecondStart, this.data.homeSecondEnd)) {
      title = "居家打卡时间第二次打卡结束时间要大于其开始时间"
    }
    // if (!this.data. || !this.data. || this.data. == 1 && (!this.data.workSecondStart || !this.data.) || !this.data.homeFirstStart || !this.data. || this.data.homeStatus == 1 && (!this.data.homeSecondStart || !this.data.homeSecondEnd) ){
    //   title2 = 1;
    // }else{
    // }
    if (title){
      wx.showToast({
        title: title,
        icon: "none",
        duration: 3000
      })
      return
    }
    app.req({
      url: "orgmini/rwSetup/saveSetup",
      method: "post",
      data: {
        "id": that.data.setId ? that.data.setId:'',
        "orgId": that.data.id,
        "workFirstStart": that.data.workFirstStart,
        "workFirstEnd": that.data.workFirstEnd,
        "workSecondStart": that.data.workSecondStart,
        "workSecondEnd": that.data.workSecondEnd,
        "workStatus": that.data.workStatus? 1:0,
        "homeFirstStart": that.data.homeFirstStart,
        "homeFirstEnd": that.data.homeFirstEnd,
        "homeSecondStart": that.data.homeSecondStart,
        "homeSecondEnd": that.data.homeSecondEnd,
        "homeStatus": that.data.homeStatus? 1:0,
        "rwSetupDetail": that.data.textarea,
        "delDetail": that.data.delDetail,
      },
      success: function (res) {
        if (200 == res.code) {
          wx.showToast({
            title: '保存成功',
            icon: 'none',
            duration: 2000
          })
          that.toggle('lock',true);
          setTimeout(()=>{
            wx.redirectTo({
              url: '/packageA/pages/epidemicSeeNew/epidemicSeeNew?id=' + that.data.id + '&isOrg=1'
            })
          },1000)
        }
      }
    })
  },
  //上次设置
  getInfo(){
    var that = this;
    var url = "orgmini/rwSetup/setupInfo";
    app.req({
      url: url,
      method: "post",
      data: {
        orgId: that.data.id
      },
      success(res){
        if(res.code == 200 && res.data){
          that.toggle("setId", res.data.id);
          that.toggle("workFirstStart", res.data.workFirstStart);
          that.toggle("workFirstEnd", res.data.workFirstEnd);
          that.toggle("workSecondStart", res.data.workSecondStart);
          that.toggle("workSecondEnd", res.data.workSecondEnd);
          that.toggle("workStatus", Boolean(res.data.workStatus * 1));
          that.toggle("homeFirstStart", res.data.homeFirstStart);
          that.toggle("homeFirstEnd", res.data.homeFirstEnd);
          that.toggle("homeSecondStart", res.data.homeSecondStart);
          that.toggle("homeSecondEnd", res.data.homeSecondEnd);
          that.toggle("homeStatus", Boolean(res.data.homeStatus * 1));
          that.toggle("textarea", res.data.rwSetupDetail);
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("平安打卡",options);
    this.toggle("id", options.id);
    this.detail();
    this.getInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // var title = ''
    // var url = ''
    // this.toggle("ismodal", false);
    // title = this.data.detail.relationName + '邀请你进行平安打卡，免费领口罩'
    // if (this.data.isOrg) {
    //   url = '/pages/orgHome/orgHome?id=' + this.data.id
    // } else{
    //   url = '/pages/epidemicSee/epidemicSee?isorg=' + this.data.isOrg + '&id=' + this.data.id
    // }
    // return {
    //   title: title,
    //   imageUrl: this.data.imageUrl[0].url,
    //   path: url
    // }
  }
})